package com.example.myapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.Toast
import com.example.android_program.data_class.movie_info
import com.example.myapplication.ui.movie.SelectCinemaActivity
import kotlinx.android.synthetic.main.activity_movie_details.*
import kotlinx.android.synthetic.main.activity_movieinfo.*
import kotlinx.android.synthetic.main.activity_movieinfo.movie_infoime
import kotlinx.android.synthetic.main.activity_movieinfo.movie_infotype
import kotlinx.android.synthetic.main.activity_movieinfo.movieacter
import kotlinx.android.synthetic.main.activity_movieinfo.movieinfoname
import kotlinx.android.synthetic.main.activity_movieinfo.movieinfopng
import kotlinx.android.synthetic.main.activity_movieinfo.movietest
import kotlinx.android.synthetic.main.activity_movieinfo.thgp
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.lang.reflect.Field
import java.net.URLEncoder
import kotlin.concurrent.thread

class MovieDetailsActivity : AppCompatActivity() {

    val movie_info: ArrayList<movie_info> = ArrayList()
    var movie_Name:String = ""
    val sever_ip = "192.168.43.8"
    val sever_ip2 = "192.168.31.197"
    val searchMovieInfo_jsp = "http://${sever_ip}:8080/JspForAndroid/searchMovieInfo.jsp"
    //val searchMovieInfo_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/searchMovieInfo.jsp"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_movie_details)



        movie_Name = intent.getStringExtra("movie_name").toString()
        Toast.makeText(this, "this is: ${movie_Name}", Toast.LENGTH_LONG).show()
        //ttttt.setText(movie_Name)

        Movieinfo_data() //数据读取
       // set_movieinfo()  //添加数据

        thgp.setOnClickListener {
            Toast.makeText(this,"求往选择影院界面", Toast.LENGTH_LONG).show()
          val intent = Intent(this, SelectCinemaActivity::class.java)//电影
            intent.putExtra("movie_name", movie_info[0].movie_name)
            intent.putExtra("movie_Name", movie_Name)
          startActivityForResult(intent, 1)//电影详情到SelectCinemaActivity

        }
    }

    private fun Movieinfo_data(){

        getAllTrainInfoJson()

        /*movie_info.add(movie_info(R.drawable.movie_3,"赤狐书生","奇幻/古装/喜剧",
            "2020-12-04 中国大陆上映/125分钟",
            "清贫书生王子进(陈立农饰)进京赶考,被来到人界取丹的狐妖白十三(李现饰)町上。为了骗取书生信任,狐妖联合各路妖鬼,设下重重陷阱。",
            R.drawable.actorinfo))*/
    }

    private fun set_movieinfo(){
        val info = movie_info[0]
        movieinfopng.setImageResource(info.movie_Src)
        movieinfoname.setText("${info.movie_name}")
        movie_infotype.setText("${info.movie_type}")
        movie_infoime.setText("${info.movie_time}")
        movietest.setText("${info.movie_test}")
        movieacter.setImageResource(info.movie_acter)
    }

    //json解析
    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                val movie_Name = movie_Name

                val requestBody = FormBody.Builder()
                    .add("movie_Name", URLEncoder.encode(movie_Name,"UTF-8"))
                    //.add("endStation", "衢州")
                    .build()

                //构建请求
                val request = Request.Builder()
                    .url(searchMovieInfo_jsp)
                    .post(requestBody)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
                val result = parseJson(responseData)
                if (responseData != null){
                    runOnUiThread{
                        //txtData.text = result
                        //更新布局
                        set_movieinfo()
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()

        try {
            //json数组
            val jsonArray = JSONArray(jsonData)
            movie_info.clear()
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_src = jsonObject.getString("movie_src")
                val movie_name = jsonObject.getString("movie_name")
                val movie_type = jsonObject.getString("movie_type")
                val movie_time = jsonObject.getString("movie_time")
                val movie_test = jsonObject.getString("movie_test")
                val movie_acter = jsonObject.getString("movie_acter")
                builder.append("$movie_src--$movie_name--$movie_type--$movie_time--$movie_test--$movie_acter, ")

                movie_info.add(movie_info(getResourceIdByString(movie_src),movie_name,movie_type,
                    movie_time,
                    movie_test,
                    getResourceIdByString(movie_acter)))
//                Looper.prepare()
//                Toast.makeText(this, builder.toString(), Toast.LENGTH_LONG).show()
//                Looper.loop()
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

}